import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  Image,
  FlatList,
  StyleSheet,
  ImageBackground,
  TouchableOpacity,
  RefreshControl,
} from 'react-native';
import {useIsFocused, useNavigation} from '@react-navigation/native';
import Toast from 'react-native-toast-message';
import {showToast} from '../utils/toastUtils';
import theme from '../utils/theme';
import {getData, saveData} from '../utils/storageUtils';
import API, {loadUserId} from '../Network/Api';
import { normalize, stringTofixed } from "../utils/commonUtils";
import {CustomText} from '../customview/CustomText';

let isMember = false;

const EventItem = ({item, onPress}) => {
  const [countdown, setCountdown] = useState('');
  const [updatedItem, setUpdatedItem] = useState(item);

  useEffect(() => {
    setUpdatedItem(item);
  }, [item]);

  useEffect(() => {
    const intervalId = setInterval(() => {
      const now = new Date();
      const targetStartTime = new Date();
      const targetEndTime = new Date();

      const [startHours, startMinutes, startSeconds] = updatedItem.cckssj
        .split(':')
        .map(Number);
      const [endHours, endMinutes, endSeconds] = updatedItem.ccjssj
        .split(':')
        .map(Number);

      targetStartTime.setHours(startHours, startMinutes, 0, 0);
      targetEndTime.setHours(endHours, endMinutes, 0, 0);
      if (isMember) {
        // 如果是会员，将开始时间提前一分钟
        targetStartTime.setMinutes(targetStartTime.getMinutes() - 1);
      }

      const oneHourBeforeStart = new Date(targetStartTime.getTime() - 3600000);
      const fiveMinutesBeforeStart = new Date(
        targetStartTime.getTime() - 300000,
      );

      let newState;

      if (now < oneHourBeforeStart) {
        setCountdown('未开始');
        newState = '0';
      } else if (now >= oneHourBeforeStart && now < fiveMinutesBeforeStart) {
        setCountdown('即将开始');
        newState = '2';
      } else if (now >= fiveMinutesBeforeStart && now < targetStartTime) {
        let countdownText;
        if (isMember) {
          const difference = targetStartTime - now;
          const hoursRemaining = Math.floor(difference / 3600000);
          const minutesRemaining = Math.floor((difference % 3600000) / 60000);
          const secondsRemaining = Math.floor((difference % 60000) / 1000);
          countdownText = `提前入场倒计时：${String(hoursRemaining).padStart(
            2,
            '0',
          )}:${String(minutesRemaining).padStart(2, '0')}:${String(
            secondsRemaining,
          ).padStart(2, '0')}`;
        } else {
          const difference = targetStartTime - now;
          const hoursRemaining = Math.floor(difference / 3600000);
          const minutesRemaining = Math.floor((difference % 3600000) / 60000);
          const secondsRemaining = Math.floor((difference % 60000) / 1000);
          countdownText = `入场倒计时：${String(hoursRemaining).padStart(
            2,
            '0',
          )}:${String(minutesRemaining).padStart(2, '0')}:${String(
            secondsRemaining,
          ).padStart(2, '0')}`;
        }
        setCountdown(countdownText);
        newState = '2';
      } else if (now >= targetStartTime && now < targetEndTime) {
        const difference = targetEndTime - now;
        const hoursRemaining = Math.floor(difference / 3600000);
        const minutesRemaining = Math.floor((difference % 3600000) / 60000);
        const secondsRemaining = Math.floor((difference % 60000) / 1000);
        setCountdown(
          `结束倒计时：${String(hoursRemaining).padStart(2, '0')}:${String(
            minutesRemaining,
          ).padStart(2, '0')}:${String(secondsRemaining).padStart(2, '0')}`,
        );
        newState = '1';
      } else if (now >= targetEndTime) {
        setCountdown('已结束');
        newState = '3';
        clearInterval(intervalId);
      }

      if (updatedItem.cczt === '1') {
        setCountdown('已关闭');
        newState = '0';
      }

      setUpdatedItem(prevItem => ({
        ...prevItem,
        state: newState,
      }));
    }, 1000);

    return () => clearInterval(intervalId);
  }, [updatedItem.ccjssj, updatedItem.cckssj, updatedItem.cczt]);

  const getTimeRangeString = () => {
    const [startHours, startMinutes] = updatedItem.cckssj
      .split(':')
      .map(Number);
    const [endHours, endMinutes] = updatedItem.ccjssj.split(':').map(Number);

    // 补零函数
    const padZero = num => String(num).padStart(2, '0');

    return `每日活动时间：${padZero(startHours)}:${padZero(
      startMinutes,
    )} ～ ${padZero(endHours)}:${padZero(endMinutes)}`;
  };

  const getCountdownView = () => {
    switch (updatedItem.state) {
      case '0':
        return <CustomText style={[styles.countdown]}>{countdown}</CustomText>;
      case '1':
        return <CustomText style={styles.countdown}>{countdown}</CustomText>;
      case '2':
        return <CustomText style={styles.countdown}>{countdown}</CustomText>;
      case '3':
        return <CustomText style={styles.countdown}>{countdown}</CustomText>;
      default:
        return <CustomText style={styles.countdown}>{countdown}</CustomText>;
    }
  };

  return (
    <TouchableOpacity style={{marginTop: 10}} onPress={() => onPress(updatedItem)}>
      <ImageBackground
        source={require('../../res/image/changci_bg.png')}
        style={styles.itemContainer}>
        <View style={styles.row1}>
          <CustomText style={styles.session}>{updatedItem.ccbt}</CustomText>
        </View>
        <View style={styles.row2}>
          <Image
            source={require('../../res/image/right_icon.png')}
            style={styles.icon}
          />
          <CustomText style={styles.time}>{getTimeRangeString()}</CustomText>
        </View>
        <View style={styles.divierStyle} />
        <View style={styles.row3}>
          <CustomText style={styles.event}>{updatedItem.ccbt}</CustomText>
        </View>
        <View style={styles.row4}>{getCountdownView()}</View>
        <Image source={theme.app.logo} style={styles.logo} />
      </ImageBackground>
    </TouchableOpacity>
  );
};

const WholesaleScreen = () => {
  const [refreshing, setRefreshing] = useState(false);
  const navigation = useNavigation();
  const [data, setData] = useState([]);
  const [totalText, setTotalText] = useState('');
  const isFocused = useIsFocused();

  useEffect(() => {
    const init = async () => {
      await loadUserId();
    };
    init();
  }, []);

  useEffect(() => {
    if (isFocused) {
      getSessions();
      getPurchasedOrder();
      getData('userInfoKey').then(userInfo => {
        if (userInfo) {
          if (
            userInfo.userBq === '1' ||
            userInfo.userBq === '3' ||
            userInfo.userBq === '6' ||
            userInfo.userBq === '7'
          ) {
            isMember = true;
          } else {
            isMember = false;
          }
        }
      });
    }
  }, [isFocused]);

  const getSessions = () => {
    try {
      API.getSessionRecordList()
        .then(async response => {
          if (response.resultCode === '1') {
            const sessionData = response.data.sessionRecord.rows || [];
            setData(sessionData);
          }
        })
        .catch(error => {
          console.error('获取场次信息失败:', error);
        });
    } catch (error) {
      console.error('获取场次失败:', error);
    } finally {
      setRefreshing(false);
    }
  };

  const getPurchasedOrder = () => {
    try {
      API.getPurchasedOrderInfoList()
        .then(async response => {
          if (response.resultCode === '1') {
            const orderData = response.data.orderInfo.rows;
            const sumOrders = response.data.orderInfo.total;
            if (sumOrders > 0) {
              let amount = 0;
              orderData.forEach(order => {
                const price = parseFloat(order.spjg);
                if (!isNaN(price)) {
                  amount += price;
                }
              });
              const str =
                '当日批发金额: ' +
                amount.toFixed(2) +
                '元 (' +
                sumOrders +
                '单)';
              setTotalText(str);
            } else if (totalText.length > 0) {
              setTotalText('');
            }
          }
        })
        .catch(error => {
          showToast({text2: '获取总购买订单数据失败！'});
        });
    } catch (error) {
      console.error('获取场次失败:', error);
    } finally {
    }
  };

  const getUserInfo = () => {
    API.userInfoReq()
      .then(async response => {
        if (response.resultCode === '1') {
          let userInfos = response.data.userInfo.rows;
          if (userInfos.length <= 0) {
            return;
          }
          let userInfo = userInfos[0];
          const localUserInfo = await getData('userInfoKey');
          localUserInfo.userStatus = userInfo.yhzt;
          await saveData('userInfoKey', localUserInfo);
        } else {
          console.error(response.showMsg);
        }
      })
      .catch(error => {
        console.error('用户信息失败:', error);
      });
  };

  const handleItemPress = async item => {
    // 1表示场次关闭，2表示场次开启
    if (item.cczt === '1') {
      await showToast({text2: '该场次已关闭！'});
      return;
    }
    const loginStatus = await getData('loginState');
    const userInfo = await getData('userInfoKey');
    if (!loginStatus) {
      await showToast({text2: '请先登录！'});
      return;
    }
    if (userInfo.userStatus === '1') {
      await showToast({text2: '请向管理员申报解锁！'});
      return;
    }
    if (!userInfo.isRealName) {
      await showToast({text2: '请先完成实名认证！'});
      return;
    }
    if (item.state === '1' || item.state === '2') {
      navigation.navigate('ProductListPage', {
        sessionInfo: item,
        isMember: isMember,
      });
    } else if (item.state === '0') {
      await showToast({
        text2: '活动未开始',
      });
    } else if (item.state === '3') {
      await showToast({
        text2: '活动已结束',
      });
    }
  };

  const onRefresh = async () => {
    setRefreshing(true);
    await getUserInfo();
    await getSessions();
  };

  return (
    <View style={styles.container}>
      {totalText !== '' ? (<View style={styles.ordersStyle}><CustomText style={styles.moneyText}>{totalText}</CustomText></View>) : null}
      <FlatList
        data={data}
        renderItem={({item}) => (
          <EventItem item={item} onPress={handleItemPress} />
        )}
        keyExtractor={item => item.id.toString()}
        contentContainerStyle={styles.listContent}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      />
      <Toast />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  listContent: {
    padding: 10,
  },
  itemContainer: {
    flexDirection: 'column',
    borderRadius: 8,
    overflow: 'hidden',
    height: 175,
  },
  row1: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 15,
    marginLeft: 15,
  },
  row2: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: 15,
    marginTop: 10,
  },
  row3: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: 15,
    marginTop: 15,
  },
  row4: {
    flexDirection: 'row',
    position: 'absolute',
    bottom: 15,
    left: 15,
  },
  session: {
    fontSize: normalize(18),
    fontWeight: 'bold',
    color: '#000',
  },
  time: {
    fontSize: normalize(14),
    color: '#000',
  },
  icon: {
    width: 6,
    height: 6,
    marginRight: 5,
  },
  event: {
    fontSize: normalize(14),
    color: '#6D7278',
    flex: 1,
  },
  status: {
    fontSize: normalize(14),
    color: 'red',
  },
  countdown: {
    fontSize: normalize(16),
    color: '#fff',
    fontWeight: '500',
  },
  logo: {
    position: 'absolute',
    bottom: 10,
    right: 10,
    width: 80,
    height: 80,
    borderRadius: 8,
  },
  divierStyle: {
    backgroundColor: '#F4F4F9',
    height: 2,
    marginHorizontal: 15,
    marginTop: 10,
  },
  ordersStyle: {
    backgroundColor: '#fff',
    paddingVertical: 10,
  },
  moneyText: {
    color: theme.colors.primary,
    alignSelf: 'center',
    fontSize: normalize(14),
  },
});

export default WholesaleScreen;
